﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using ST.Buz.Base.Enums;
using ST.Common.Util.Security;
using ST.Buz.Base.ViewModel;
using Microsoft.Data.SqlClient;

namespace ST.Buz.Service
{
	public partial interface IServiceSysUserOAuth
	{
		/// <summary>
		/// 获取oauth认证绑定的默认用户
		/// </summary>
		/// <returns></returns>
		Sys_User GetFirstOrDefaultUser(int oauthID);

		/// <summary>
		/// 获取与指定用户绑定的第三方登录列表
		/// </summary>
		/// <param name="searchModel"></param>
		/// <returns></returns>
		PageData GetOAuthListByUserID(UserSession sessionCurrent, VMS_Sys_UserOAuth searchModel);

		void DeleteByUserID(int userID);
	}

	public partial class ServiceSysUserOAuth
	{
		public ServiceSysUserOAuth(BuzContext ctx,
			ILogger<ServiceSysUserOAuth> log)
		{
			context = ctx;
			logger = log;
		}

		/// <summary>
		/// 获取oauth认证绑定的默认用户
		/// </summary>
		/// <returns></returns>
		public Sys_User GetFirstOrDefaultUser(int oauthID)
		{
			Sys_User result = null;
			var usersBinded = 
							(from u in context.SysUser
							   join uo in context.SysUserOAuth on u.ID equals uo.UserID
							   where uo.OAuthID == oauthID
							   select new
							   {
								   User = u,
								   uo.Preferred
							   }).ToList();
			if (usersBinded.Count > 0)
			{
				var firstBind = usersBinded.FirstOrDefault(m => m.Preferred);
				if (firstBind != null)
				{
					result = firstBind.User;
				}
				else
				{
					result = usersBinded[0].User;
				}
			}
			return result;
		}

		/// <summary>
		/// 获取与指定用户绑定的第三方登录列表
		/// </summary>
		/// <param name="searchModel"></param>
		/// <returns></returns>
		public PageData GetOAuthListByUserID(UserSession sessionCurrent, VMS_Sys_UserOAuth searchModel)
		{
			PageData result = null;
			try
			{
				//searchModel.Validate();

				var query = (from o in context.SysOAuth
							 join uo in context.SysUserOAuth on o.ID equals uo.OAuthID
							 where uo.UserID == searchModel.userid
							 select new
							 {
								 o.AppID,
								 o.OpenID,
								 o.UnionID,
								 o.AvatarUrl,
								 o.NickName,
								 o.Country,
								 o.Province,
								 o.City,
								 o.District,
								 o.Town,
								 o.DetailAddress,
								 uo.AddDate,
								 uo.Preferred,
								 o.ID,
								 Type = o.TypeText,
								 Gender = o.GenderText,
							 }).AsNoTracking();
				switch (searchModel.sortby)
				{
					default:
						query = searchModel.orderby == Common.Util.Mvc.SortOrder.Ascending ? query.OrderBy(e => e.ID) : query.OrderByDescending(e => e.ID);
						break;
				}
				result = new PageData(searchModel.pnum.Value, searchModel.psize.Value);
				result.Load(query);
			}
			catch (BuzException ex)
			{
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, "获取分页数据出错");
				throw new BuzException("获取分页数据失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
			return result;
		}

		public void DeleteByUserID(int userID)
		{
			context.Database.ExecuteSqlRaw("DELETE FROM Sys_UserOAuth WHERE UserID={0}", userID);
		}
	}
}